package com.powerbank.usercenter.mq.consumer;

import com.powerbank.common.event.payment.PaymentSuccessEvent;
import com.powerbank.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 支付成功事件消费者
 * 处理支付成功后的用户积分奖励
 */
@Slf4j
@Component
@RocketMQMessageListener(
    topic = "PowerBank-Payment-Topic",
    selectorExpression = "PAYMENT_SUCCESS",
    consumerGroup = "user-center-payment-consumer"
)
public class PaymentSuccessConsumer implements RocketMQListener<PaymentSuccessEvent> {

    @Autowired
    private UserService userService;

    @Override
    public void onMessage(PaymentSuccessEvent event) {
        try {
            log.info("收到支付成功事件: paymentId={}, userId={}, amount={}", 
                    event.getPaymentId(), event.getUserId(), event.getAmount());

            // 根据支付金额给用户奖励积分（1元=1积分）
            int points = event.getAmount().intValue();
            if (points > 0) {
                userService.addUserPoints(
                    event.getUserId(), 
                    points, 
                    "支付成功奖励，支付金额：" + event.getAmount()
                );
                
                log.info("用户积分奖励成功: userId={}, points={}", event.getUserId(), points);
            }

        } catch (Exception e) {
            log.error("处理支付成功事件失败: paymentId={}, userId={}", 
                     event.getPaymentId(), event.getUserId(), e);
            throw new RuntimeException("支付成功事件处理失败", e);
        }
    }
}